package com.worklikedance.util;

import java.io.StringReader;
import java.util.Iterator;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.worklikedance.util.Log;

public class DOMParser {
	public static final String TAG = "DOMParser";
	
	public static NodeList queryNodes(String xmlDocument, String xpathString, final String namespaceS, final String namespaceNS2) {
		//
		XPath xPath = XPathFactory.newInstance().newXPath();
		assert(xPath != null);
		
		xPath.setNamespaceContext(new NamespaceContext() {
			@Override
			public Iterator getPrefixes(String arg0) {
				return null;
			}
			
			@Override
			public String getPrefix(String arg0) {
				return null;
			}
			
			@Override
			public String getNamespaceURI(String arg0) {
				if ("S".equals(arg0)) {
					return namespaceS;
				}
				else if ("ns2".equals(arg0)) {
					return namespaceNS2;
				}
				
				return null;
			}
		});
		
		//
		InputSource source = new InputSource(new StringReader(xmlDocument));
		
		//
		NodeList nodes = null;
		
		try {
			nodes = (NodeList) xPath.evaluate(xpathString, source, XPathConstants.NODESET);
		}
		catch (XPathExpressionException e) {
			e.printStackTrace();
			
			Log.d(TAG, e.getLocalizedMessage());
		}
		
		return nodes;
	}
}
